<?php

namespace App\Http\Resources;

use App\Models\Factory;
use Carbon\Carbon;
use Illuminate\Http\Resources\Json\ResourceCollection;

class FactoryCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        //."?imageView2/1/w/105/h/105"
        return [
            'code' => 200,
            'message' => '请求成功',
            'data' => $this->collection->map(function ($item) {
                /**
                 * @var $item \App\Models\Factory
                 */
                if ($item->type == 1) {
                    $unit = '元/㎡';
                    $totalUnit='元/月';
                    $total_price=$item->total_price;
                } elseif ($item->type == 2) {
                    $unit = '元/㎡';
                    $totalUnit='万元';
                    $total_price=   round($item->total_price/10000,1);
                } else {
                    $unit =  '元/月';
                    $totalUnit='万元';
                    $total_price=    round($item->total_price/10000,1);;
                }
                return [
                    'factory_id' => $item->id,
                    'title' => $item->title,
                    'logo' => \Storage::url($item->logo)."?imageView2/1/w/200/h/200",
                    'tag' => $item->tag->reject(function ($value, $key) {
                        return $key > 2;
                    })->pluck('name')->toArray(),
                    'address'=>($item->city->name ?? '').($item->town->name ?? ''),
                    'type'=>$item->type,
                    'area' =>  $item->area ,
                    'price' =>$item->price,
                    'price_unit'=>$unit,
                    'total_price'=>$total_price,
                    'total_unit'=>$totalUnit,
                    'lat'=>$item->baidu_lat,
                    'lng'=>$item->baidu_lng,
                    'shenhe'=>$item->shenhe,
                    'shenhe_desc'=>Factory::$shenhe[$item->shenhe] ?? '',
                    'created_at'=>Carbon::parse($item->created_at)->format('Y-m-d'),
              ];
            })
        ];
    }
}
